import { useEffect, useState } from "react"
import PropTypes from "prop-types"
import { Button, Space } from "antd"
import useRowSelection from "../../hooks/useRowSelection"
import useQueryList from "../../hooks/useQueryList"
import CommonTable from "./CommonTable"
import CommonModal from "./CommonModal"
import CommonFilterItem from "./CommonFilterItem"

const CommonModalPicker = ({
  saveType = 'id',
  multiple = true,
  typeName,
  btnText,
  queryAction,
  disabledKeys,
  disabled,
  columns,
  filters,
  onPick,
  getResData = (res) => {
    return res.data
  }
}) => {

  const [visible, setVisible] = useState(false)

  const {
    listData,
    loading,
    doQueryList,
    queryValues,
    changeQueryValues
  } = useQueryList({
    apis: { queryList: queryAction },
    isAutoQuery: false,
    moduleName: typeName,
    getResData
  })

  const {
    selectedRowKeys,
    setSelectedRowKeys,
    rowSelection
  } = useRowSelection({
    multiple,
    disabledKeys
  })

  const handleShow = () => {
    setVisible(true)
  }

  const handleCancel = () => {
    setSelectedRowKeys([])
    setVisible(false)
  }

  const handleConfirm = () => {
    if (saveType === 'row') {
      onPick(listData.filter(el => {
        return selectedRowKeys.includes(el.id)
      }))
    } else {
      onPick(selectedRowKeys)
    }
    handleCancel()
  }

  useEffect(() => {
    doQueryList()
  }, [queryValues])

  useEffect(() => {
    if (visible) {
      doQueryList()
    }
  }, [visible])

  const formatedColumns = columns.map(el => {
    if (el.searchKey) {
      return CommonTable.createColumn.searchResult({
        ...el,
        searchWord: queryValues[el.searchKey]
      })
    } else {
      return el
    }
  })

  const renderFooter = () => {
    return <div className="between-box">
      <Space>
        <div style={{ lineHeight: '32px' }}>
          <span> 已选中：<b>{selectedRowKeys.length}</b> 项</span>
          {
            selectedRowKeys.length > 0 &&
            <Button
              type="link"
              onClick={() => {
                setSelectedRowKeys([])
              }}
            >取消选中</Button>
          }
        </div>
      </Space>
      <Space>
        <Button
          type="primary"
          disabled={selectedRowKeys.length === 0}
          onClick={handleConfirm}
        >确定</Button>
      </Space>
    </div>
  }

  const renderHeader = () => {
    if (filters && filters.length > 0) {
      return <div className="between-box mb12">
        <Space>
          {
            filters.map(el => {
              switch (el.type) {
                case 'search':
                  return <CommonFilterItem.Search
                    key={el.name}
                    label={el.label}
                    field={el.name}
                    queryValues={queryValues}
                    onChangeQueryValues={changeQueryValues}
                  ></CommonFilterItem.Search>
                case 'select':
                  return <CommonFilterItem.Select
                    key={el.name}
                    label={el.label}
                    field={el.name}
                    queryValues={queryValues}
                    onChangeQueryValues={changeQueryValues}
                    options={el.options}
                  ></CommonFilterItem.Select>
              }
            })
          }
        </Space>
      </div>
    } else {
      return null
    }
  }

  return <>
    <Button
      type="primary"
      onClick={handleShow}
      disabled={disabled}
    >{btnText ? btnText : `添加${typeName}`}</Button>
    <CommonModal
      width={720}
      title={`选择${typeName}`}
      visible={visible}
      onCancel={handleCancel}
      footer={renderFooter()}
      header={renderHeader()}
    >
      <div style={{ height: 300 }}>
        <CommonTable
          loading={loading}
          dataSource={listData}
          columns={formatedColumns}
          rowSelection={rowSelection}
          onRow={(rowData) => ({
            onClick: () => {
              if (!multiple) {
                setSelectedRowKeys([rowData.id])
              }
            },
            style: { cursor: 'default' }
          })}
        ></CommonTable>
      </div>
    </CommonModal>
  </>
}

CommonModalPicker.propTypes = {
  saveType: PropTypes.oneOf(['id', 'row']),
  multiple: PropTypes.bool,
  typeName: PropTypes.string.isRequired,
  btnText: PropTypes.string,
  queryAction: PropTypes.func,
  disabledKeys: PropTypes.array,
  disabled: PropTypes.bool,
  columns: PropTypes.array.isRequired,
  filters: PropTypes.array,
  onPick: PropTypes.func.isRequired,
  getResData: PropTypes.func
}

export default CommonModalPicker